package com.start.common.tools;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class UrlTools {
    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 路径匹配
     * @param pattern 匹配表达式
     * @param url     匹配路径
     * @return
     */
    public static boolean antPathMatcher(String pattern, String url) {
        return antPathMatcher.match(pattern, url);
    }

    /**
     * 路径匹配
     * @param patterns 匹配表达式
     * @param url      匹配路径
     * @return
     */
    public static boolean antPathMatcher(Collection<String> patterns, String url,boolean defVal) {
        if(StringUtils.isAllBlank(url)){
            return defVal;
        }
        if(patterns==null||patterns.isEmpty()){
            return defVal;
        }
        for (String pattern : patterns) {
            if (antPathMatcher.match(pattern, url)) return true;
        }
        return false;
    }

    /**
     * 路径匹配
     * @param pattern 匹配表达式
     * @param urls    匹配路径
     * @return
     */
    public static boolean antPathMatcher(String pattern, Collection<String> urls) {
        for (String url : urls) {
            if (antPathMatcher.match(pattern, url)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 路径匹配
     * @param pattern 匹配表达式
     * @param urls    匹配路径
     * @return
     */
    public static List<String> antPathMatcherList(String pattern, Collection<String> urls) {
        List<String> result = new ArrayList<>();
        for (String url : urls) {
            if (antPathMatcher.match(pattern, url)) {
                result.add(url);
            }
        }
        return result;
    }

    /**
     * 路径匹配
     * @param patterns 匹配表达式
     * @param url      匹配路径
     * @return
     */
    public static List<String> antPathMatcherList(Collection<String> patterns, String url) {
        List<String> result = new ArrayList<>();
        for (String pattern : patterns) {
            if (antPathMatcher.match(pattern, url)) {
                result.add(url);
            }
        }
        return result;
    }
}
